module.exports = () => {
	return async function auth(ctx, next) {
		const currenUrl = ctx.request.url

		if (currenUrl.includes('/api/web')) return await next()

		//后台只有admin用户才能通过
		const { whiteUsers } = ctx.app.config.auth
		const { whiteUrls } = ctx.app.config.auth // 黑名单
		const { secret } = ctx.app.config.jwt
		let noValiDate = whiteUrls.some((item) => currenUrl.includes(item)) // 当前路径在白名单中
		if (noValiDate) {
			return await next()
		} else {
			const { authorization } = ctx.request.header
			// console.log(ctx.request.header)
			if (authorization) {
				const token = authorization.replace('Bearer ', '')
				const { oldUser } = await ctx.app.jwt.verify(token, secret)
				// console.log(oldUser)
				ctx.session.userInfo = oldUser // 将当前解析到的用户存储到回话中
				if (!whiteUsers.includes(oldUser.username)) {
					await next()
				} else {
					ctx.status = 403
					ctx.body = {
						code: 403,
						msg: '无权限',
					}
				}
			} else {
				await next()
			}
		}
	}
}
